const app = getApp();
var http = require('../../../../service/http.js'); //请求类
var util = require('../../../../utils/util.js'); //工具类
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //输入框操作
    searchVal: '',
    searchHistory: [], //搜索历史
    searchList: [], //搜索出来的商品列表
    total: 0, //分页总数
    pageNo: 1, //当前页数
    second: 0, //搜索计时
    timeout: '', //停止计时
    pageUrl: '', //跳转url

    shopuid: '', //店铺id
    shopName: '', //店铺名称
    isOwnShop: '', //是否是自己有分销店铺
    //加载更多
    showLoadding: false, //加载动画gif
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let shopInfo = wx.getStorageSync('shopInfo');
    let searchHistory = wx.getStorageSync('searchHistory');
    if (searchHistory) {
      this.setData({
        searchHistory: searchHistory,
        shopuid: shopInfo.shopuid || ''
      })
    }
  },
  handerSearch: function(e) {
    this.setData({
      searchVal: e.detail.value
    })
    util.throttle(this.searchListFun, 1000);
  },

  //查询搜索列表
  searchListFun() {
    console.log('searchList根据输入搜索商品')
    let [pageNo, pageSize, second, searchVal] = [1, app.data.pageSize, this.data.second, this.data.searchVal];
    console.log('查询内容=' + searchVal);
    let shopInfo = wx.getStorageSync('shopInfo');
    let shopuid = '';
    if (shopInfo.shopuid != undefined && shopInfo.shopuid != null && shopInfo.shopuid != '') {
      shopuid = shopInfo.shopuid;
    }
    if (searchVal) {
      this.setData({
        showLoadding: true
      })
      http.getReq('/weixin/item/itemList', {
        itemName: searchVal,
        pageNo: pageNo,
        pageSize: pageSize,
        shopuid: shopuid, //用于根据店铺id查找该店铺上架的商品
        cityName: app.data.cityName || '北京', //获取地理位置
      }, (res) => {
        // console.log('itemList',res);
        let searchList = res.data;

        let searchHistory = wx.getStorageSync('searchHistory'); //本地历史搜索

        this.saveSearchVal(searchVal); //有搜索结果 将搜索值存入本地历史搜索

        this.setData({
          searchList: searchList,
          total: res.total,
          pageNo: pageNo,
          showLoadding: false
        })
      });

    } else { //搜索内容为空
      //初始化商品列表
      this.setData({
        searchList: [],
        total: 0,
        pageNo: 1,
        searchVal: searchVal
      })
    }
  },
  //存储搜索历史
  saveSearchVal: function(searchVal) {
    let [searchHistory, localSearch] = [wx.getStorageSync('searchHistory'), []] //本地历史搜索
    if (searchHistory) { //有搜索历史
      searchHistory.reverse(); //将倒叙变为正序
      //判断搜索内容是否包含在搜索历史中
      if (searchHistory.indexOf(searchVal) > -1) { //包含
        for (let s = 0; s < searchHistory.length; s++) {
          if (searchHistory[s] == searchVal) {
            searchHistory.splice(s, 1); //移除该元素
          }
        }
      }
      searchHistory.push(searchVal) //将搜索值放在首位

      searchHistory.reverse(); //倒叙排列

      if (searchHistory.length > 2) { //列表长度为2，多余删除
        searchHistory.pop();
      }
      this.setData({
        searchHistory: searchHistory
      })

      wx.setStorageSync('searchHistory', searchHistory);
    } else { //无搜索历史
      localSearch.push(searchVal);
      wx.setStorageSync('searchHistory', localSearch);
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.data.shopInfoTimeOut === true) { //非分享且已经过期，清除店铺信息
      console.log('店铺信息已过期，重新加载 app.checkSession()');
      app.checkSession();
    }
    this.setData({
      pageUrl: ''
    })
  },

  //取消搜索
  cancelSearch: function() {
    wx.navigateBack({
      delta: 1,
    })
  },
  //删除搜索记录
  delSearchHistory: function(e) {
    let index = e.currentTarget.dataset.index;

    let searchHistory = wx.getStorageSync('searchHistory');
    searchHistory.splice(index, 1); //移除数组；
    this.setData({
      searchHistory: searchHistory
    })
    wx.setStorageSync('searchHistory', searchHistory); //本地搜索记录
  },
  //加载更多
  onReachBottom: function(e) {
    console.log('加载更多');
    let [pageNo, total, searchVal, searchList] = [this.data.pageNo, this.data.total, this.data.searchVal, this.data.searchList];

    if (pageNo < total) {
      pageNo = pageNo + 1;
      this.itemList(searchVal, pageNo, searchList);
    }
  },
  //根据历史记录搜索商品列表
  searchByHistory: function(e) {
    console.log(e);
    let [searchVal, pageNo, searchList] = [e.currentTarget.dataset.val, 1, []];
    this.itemList(searchVal, pageNo, searchList);
    //改变搜索历史位置
    let searchHistory = wx.getStorageSync('searchHistory');
    for (let s = 0; s < searchHistory.length; s++) {
      if (searchHistory[s] == searchVal) {
        searchHistory.splice(s, 1); //移除该元素
        searchHistory.push(searchVal);
      }
    }
    searchHistory.reverse();
    console.log(searchHistory);
    wx.setStorageSync('searchHistory', searchHistory);

  },

  itemList: function(searchVal, pageNo, searchList = []) { //根据搜索内容搜索商品列表
    // console.log('searchList', searchList);
    //显示加载
    this.setData({
      showLoadding: true, //加载动画gif
    })
    let [setProList, pageSize] = [[], app.data.pageSize];//加载分页的商品列表（用于局部刷新）
    let shopInfo = wx.getStorageSync('shopInfo');
    let shopuid = '';
    if (shopInfo.shopuid != undefined && shopInfo.shopuid != null && shopInfo.shopuid != '') {
      shopuid = shopInfo.shopuid;
    }
    
    http.getReq('/weixin/item/itemList', {
      itemName: searchVal,
      pageNo: pageNo,
      pageSize: pageSize,
      shopuid: shopuid, //用于根据店铺id查找该店铺上架的商品
      cityName: app.data.cityName || '北京', //获取地理位置
    }, (res) => {
      
      let newList = res.data; //返回分页商品
     // console.log('newList', newList);
      if (pageNo > 1) {
        for (let item of newList){
          setProList[`searchList[${searchList.length}]`] = item;
          searchList.length++;
        }
        this.setData({
          ...setProList
        })
        // console.log('setProList', ...setProList);
        

      } else {//第一次加载商品
        searchList.push(...newList);
        this.setData({
          searchList: searchList
        })
      }
      // console.log('searchList', searchList);
      //返回符合条件的列表
      this.setData({
        total: res.total,
        pageNo: pageNo,
        searchVal: searchVal,
        showLoadding: false, //加载动画gif
      })

    });

  },
  selectProductById: function(e) { //根据商品id 查商品详情
    this.setData({
      productId: e.currentTarget.dataset.productid,
      pageUrl: '/pages/product/product'
    })
    util.throttle(app.selectProductById, 500, this);
    // app.selectProductById(this)
  },
  //------------------未开通服务提示----------------------
  unOpen: function() {
    app.unOpen();
  },
  //商品列表缩略图 图片加载失败出现错误时替换图片路径
  errImg: function(e) {
    console.log(e);
    let proIndex = e.currentTarget.dataset.proindex; //商品下标
    let isSellHot = e.currentTarget.dataset.isSellHot; //是否是热销列表
    let searchList = this.data.searchList;
    this.setData({
      searchList: app.errImg(searchList, proIndex) //返回products 更改thumbImgs路径
    })
  },
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
  },

})